/**
 * Created by u_zhouzh on 2017/10/16.
 */

var storage = window.localStorage
function Cache () {
  this.put = function (key, value) {
    	this.remove(key)
    if (typeof storage !== 'undefined') { storage.setItem(key, value) }
  }

  this.get = function (key) {
    if (typeof storage !== 'undefined') { return storage.getItem(key) } else { return null }
  }

  this.remove = function (key) {
    if (typeof storage !== 'undefined') { storage.removeItem(key) }
  }

  this.clear = function () {
    if (typeof storage !== 'undefined') { storage.clear() }
  }
}

// -------------------------------------------------------------------
// MAIN
// -------------------------------------------------------------------
var cache = new Cache()

export function add2Cache (key, value) {
  cache.remove(key)
  if (typeof value === 'object') {
    value = JSON.stringify(value)
    value = 'object_' + value
  }
  //    console.log("保存:" + value);
  cache.put(key, value)
  // log.debug( storage );
}

export function getFromCache (key) {
  var value = cache.get(key)
  if (value != null && value.indexOf('object_') == 0) {
    value = value.substr(7)
  }
  return value
//    return cache.get( key );
}

export function removeFromCache (key) {
  var value = cache.get(key)
  if (value != null) {
    cache.remove(key)
  }
}

export function clearCache () {
  cache.clear()
}

// export default{
// Cache:Cache,
// add2Cache:add2Cache,
// getFromCache:getFromCache,
// removeFromCache:removeFromCache,
// clearCache: clearCache
// }
